package com.szcinda.service.dto.customColumns;

import com.szcinda.repository.CustomColumns;
import com.szcinda.repository.CustomColumnsRepository;
import com.szcinda.repository.FeeItem;
import com.szcinda.repository.FeeItemRepository;
import com.szcinda.service.SnowFlakeFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CustomColumnsServiceImpl implements CustomColumnsService {

    private final CustomColumnsRepository customColumnsRepository;
    private final SnowFlakeFactory snowFlakeFactory;
    private final FeeItemRepository feeItemRepository;

    public CustomColumnsServiceImpl(CustomColumnsRepository customColumnsRepository, FeeItemRepository feeItemRepository) {
        this.customColumnsRepository = customColumnsRepository;
        this.feeItemRepository = feeItemRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public void update(CustomColumnsDto customColumnsDto) {
        CustomColumns customColumns = customColumnsRepository.findByUserIdAndTableName(customColumnsDto.getUserId(), customColumnsDto.getTableName());
        if (customColumns == null) {
            customColumns = new CustomColumns();
            customColumns.setUserId(customColumnsDto.getUserId());
            customColumns.setTableName(customColumnsDto.getTableName());
            customColumns.setId(snowFlakeFactory.nextId("CC"));
        }
        customColumns.setColumns(String.join(",", customColumnsDto.getColumns()));
        customColumnsRepository.save(customColumns);
    }

    @Override
    public List<String> getByUser(String userId, String tableName) {
        CustomColumns customColumns = customColumnsRepository.findByUserIdAndTableName(userId, tableName);
        List<String> columns = new ArrayList<>();
        if (customColumns != null) {
            Collections.addAll(columns, customColumns.getColumns().split(","));
        }
        return columns;
    }

    @Override
    public String getColumnsByUser(String userId, String tableName) {
        CustomColumns customColumns = customColumnsRepository.findByUserIdAndTableName(userId, tableName);
        return customColumns == null ? null : customColumns.getColumns();
    }

    @Override
    public List<String> getFeeNameList() {
        List<FeeItem> feeItems = feeItemRepository.findAll();
        List<String> feeNames = feeItems.stream().map(FeeItem::getName).distinct().collect(Collectors.toList());
        if (!feeNames.contains("报关费")) {
            feeNames.add("报关费");
        }
        if (!feeNames.contains("报关联单费")) {
            feeNames.add("报关联单费");
        }
        if (!feeNames.contains("超期堆存费")) {
            feeNames.add("超期堆存费");
        }
        return feeNames;
    }
}
